import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app/data_model.dart';
import 'package:http/http.dart' as http;

class HttpIcan extends StatefulWidget {
  const HttpIcan({super.key});

  @override
  State<HttpIcan> createState() => _HttpIcanState();
}

class _HttpIcanState extends State<HttpIcan> {
  get _getBtn =>
      ElevatedButton(onPressed: onPressed, child: const Text('发送请求'));
  String resultShow = '';

  get _doPost => ElevatedButton(onPressed: onPressed3, child: const Text('发送post请求'));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('HttpIcan')),
      body: Column(children: [_getBtn, Text(resultShow),_doPost]),
    );
  }

  void onPressed() async {
    var uri = Uri.parse(
      'http://127.0.0.1:4523/m2/5951398-0-default/266599765',
    );
    var res = await http.get(uri);
    if (res.statusCode == 200) {
      setState(() {
        // resultShow = res.body;
        var map = jsonDecode(res.body);
        var resModal = ResponseModel.fromJson(map);
        resultShow = resModal.msg;
      });
    } else {
      setState(() {
        resultShow = res.statusCode.toString();
      });
    }
  }

  void onPressed2() async{
    var uri = Uri.parse(
      'http://127.0.0.1:4523/m2/5951398-0-default/266635295',
    );
    var params = {
      'p':'1'
    };
    var res = await http.post(uri,body: params);
    if (res.statusCode == 200) {
      setState(() {
        resultShow = res.body;
      });
    } else {
      setState(() {
        resultShow = res.statusCode.toString();
      });
    }
  }

  void onPressed3() async{
    var uri = Uri.parse(
      'http://127.0.0.1:4523/m2/5951398-0-default/266635295',
    );
    var params = {
      'p':'1'
    };

    var res = await http.post(uri,body: jsonEncode(params),headers: {
      "content-type":"application/json"
    });
    if (res.statusCode == 200) {
      setState(() {
        resultShow = res.body;
      });
      var map = jsonDecode(res.body);
    } else {
      setState(() {
        resultShow = res.statusCode.toString();
      });
    }
  }
}
